// Package udp.
// creator 2022-02-25 02:15:08
// Author  zhenxinma.
package udp

import (
	"context"
	"crypto/tls"
	"fmt"
	"github.com/lucas-clemente/quic-go"
	"io"
)

const Addr = "localhost:9999"

type Server struct {
	Addr string
}

func NewUdpServer(addr string) *Server {

	if addr == "" {
		addr = Addr
	}
	return &Server{
		Addr: addr,
	}
}

func (s *Server) Run(config *tls.Config) {

	listener, err := quic.ListenAddr(s.Addr, config, nil)
	if err != nil {
		fmt.Println("Run err : ", err.Error())
		return
	}

	fmt.Println("udp run port:9999 ...")
	for {

		sess, err := listener.Accept(context.Background())
		if nil != err {
			fmt.Println("Accept err: ", err.Error())
			return
		} else {
			// 处理本次请求.
			// processRequest不会更改改结构体,所以说不需要使用指针.
			go s.processRequest(sess)
		}
	}
}

func (s *Server) processRequest(sess quic.Session) {

	stream, err := sess.AcceptStream(context.Background())
	if err != nil {
		panic(err)
	} else {
		var cache []byte
		io.ReadFull(stream, cache)
		fmt.Println("server get: ", string(cache))
	}
}

type loggingWriter struct{ io.Writer }

func (w loggingWriter) Write(b []byte) (int, error) {
	fmt.Printf("Server: Got '%s'\n", string(b))
	return w.Writer.Write(b)
}
